package top.fangwenmagician.calculationstring.operator;

import top.fangwenmagician.calculationstring.ProcessControl;
import top.fangwenmagician.calculationstring.exception.CalculationException;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 除法运算符
 */
public class Divide extends A_NormalRegularOperator {
    /**
     * 保留几位小数，默认保留2位小数
     */
    private final int scale;
    /**
     * 舍入模式{@link RoundingMode}，默认四舍五入
     */
    private final RoundingMode roundingMode;

    public Divide() {
        scale = 2;
        roundingMode = RoundingMode.HALF_UP;
    }

    public Divide(int scale) {
        this.scale = scale;
        roundingMode = RoundingMode.HALF_UP;
    }

    public Divide(RoundingMode roundingMode) {
        scale = 2;
        this.roundingMode = roundingMode;
    }

    public Divide(int scale, RoundingMode roundingMode) {
        this.scale = scale;
        this.roundingMode = roundingMode;
    }

    @Override
    public String regularText() {
        return "([\\d.]+)\\/([\\d.]+)";
    }

    @Override
    public int priority() {
        return 100;
    }

    @Override
    public String calculation(String[] captureStrings, ProcessControl processControl) throws Exception {
        if (captureStrings.length >= 3) {
            String s1 = captureStrings[1];
            String s2 = captureStrings[2];
            try {
                Double.parseDouble(s1);
            } catch (Exception e) {
                throw new CalculationException("\"" + s1 + "\"无法转换为double", e);
            }
            try {
                Double.parseDouble(s2);
            } catch (Exception e) {
                throw new CalculationException("\"" + s2 + "\"无法转换为double", e);
            }
            return new BigDecimal(s1).divide(new BigDecimal(s2), scale, roundingMode).toString();
        } else {
            throw new CalculationException("未捕获到足够的数据，请检查表达式是否错误");
        }
    }
}
